<template>
  <t-w-info-box class="info-box" :info="twInfo" @refresh="handleClickRefresh"></t-w-info-box>
  <!--    展示板-->
  <div class="part">
    <Showboard :text-list="textList" :curr-index="currTextIndex" :font-size="45"></Showboard>
<!--    <ChineseShowboard   :text-list="textList" :curr-index="currTextIndex" :font-size="35"></ChineseShowboard>-->
  </div>

  <!--    进度条-->
  <div class="text-practice-progress flex-row-center">
    <y-progress color="var(--theme-color)"
                :percent="currTextIndex/textList.length*100"
                v-show="globalSetting.showProgress"
    ></y-progress>
  </div>
  <div class="flex-col-center chinese-input-box">
    <input v-model="inputText" ref="input" class="chinese-input" maxlength="1" @keydown.enter="handleInputEnter">
    <el-icon class="margin-col-10 jump" :size="25" color="tomato"><Top /></el-icon>
    <div style="font-size: 14px;color: #a8a8a8">点击输入</div>
  </div>
</template>

<script lang="ts" setup>

import {defineProps, onMounted, ref, watch,defineEmits} from "vue";

import globalSettingStore from "@/store/globalSettingStore";
import {RecordItem, RecordStatus, TWInfo} from "@/ts/record";

import YProgress from "@/components/progress/YProgress.vue";

import useTimer from "@/hooks/useTimer"
import {ElMessage} from "element-plus";
import TWInfoBox from "@/components/infobox/TWInfoBox.vue";
import ChineseShowboard from "@/components/showboard/ChineseShowboard.vue";
import useVoice from "@/hooks/useVoice";
import {Top} from "@element-plus/icons";
import {Tollgate} from "@/ts/scheme";
import Showboard from "@/components/showboard/Showboard.vue";

let {speakChinese,playErrorVoice} = useVoice();


let props = defineProps<{
  tollgate:Tollgate
}>()
let emit=defineEmits<{
  (e:"end",val:RecordItem[]):void
}>()


// 用户输入的内容
let inputText=ref("")
// 输入框ref对象
let input=ref()
onMounted(()=>{
  input.value.focus()
})
// 用于显示的文字数组
let textList = ref<Array<RecordItem>>([])
// 用于记录结果的数组
let resultList =ref<Array<RecordItem>>([])
// 文字索引
let currTextIndex = ref(0)
// 全局设置 store
const {globalSetting}=globalSettingStore()


// 打字信息
let twInfo=ref<TWInfo>({
  currNum: 0,
  errorNum: 0,
  rightNum: 0,
  time: 0,
  total: 0
})
const defaultTwInfo={
  currNum: 0,
  errorNum: 0,
  rightNum: 0,
  time: 0,
  total: 0
}
// 定时器
let {time,startTime,stopTime} = useTimer();
startTime()
// 监测文字数组长度
watch(()=>props.tollgate,(newV)=>{
  init()
},{immediate:true})
// 监测当前索引变化
watch(currTextIndex,(newV)=>{
  let len=props.tollgate.content.length
  if(newV === len){
    end()
    return
  }
  // 修改twinfo的当前索引
  if( newV < len){
    twInfo.value.currNum =newV
  }

})

// 监测定时器
watch(time,(newV)=>{
  twInfo.value.time=newV
})

function init(){
  // 输入清空
  inputText.value=""
  // 索引归零
  currTextIndex.value=0
  // 显示文字归零
  textList.value=getRecordItemList(props.tollgate.content)
  // 打字结果归零
  resultList.value=[]
  // 打字信息归零
  twInfo.value=defaultTwInfo
  // 清空定时器
  stopTime()
  // 开启定时器
  startTime()
}
function hasNext():boolean{
  return currTextIndex.value < textList.value.length
}
// 获取当前索引指向的RecordItem
function getCurrItem():RecordItem{
  let index = hasNext()?currTextIndex.value:textList.value.length-1
  return textList.value[index];
}

// 根据string 内容生成RecordItem[]
function getRecordItemList(content:string): Array< RecordItem> {
  let textList: Array<RecordItem> = []
  // TODO 此处仅为测试时使用，需修改具体实现
  let s = content;
    for (let ch of s) {
      textList.push({
        value:ch,
        status:RecordStatus.VOID
      })
    }

  return textList
}

// 成功
function success(){
  let currItem = getCurrItem();
  // 记录结果,如果为VOID=>SUCCESS;如果ERROR不push
  if(currItem.status === RecordStatus.VOID){
    resultList.value.push({
      status: RecordStatus.SUCCESS,
      value: currItem.value
    })
  }
  // 更新状态
  currItem.status=RecordStatus.SUCCESS
  twInfo.value.rightNum++
  // 指针前移
  currTextIndex.value++
  // 输入框置空
  inputText.value=""
  //   播放读音（暂停使用，存在堆栈溢出问题，暂没查明原因2024.1.21）
  // speakChinese(currItem.value)

}
// 失败
function error(){
  let currItem = getCurrItem();
  twInfo.value.errorNum++
  // 记录结果
  resultList.value.push({
    status: RecordStatus.ERROR,
    value: currItem.value
  })
  playErrorVoice()

  // 修改显示
  currItem.status=RecordStatus.ERROR
}
// 结束回调
function end(){
  // TODO emit("end",完成记录Record)
  // 停止计时器
  stopTime()
  // 发送end事件
  emit('end',resultList.value)
}



// 判断当前输入是否正确
watch(inputText,(newV)=>{
  // 空值和索引越界
  if(newV === "" || !hasNext()){
    return
  }
  let currItem = getCurrItem()
  inputText.value === currItem.value?success():error()
})



function handleClickRefresh(){
  init()
  ElMessage({
    type:"success",
    message:"刷新成功"
  })
}
function handleInputEnter(){
  let currItem = getCurrItem();
  if(currItem.value === "\n"){
    success()
  }
}
</script>

<style scoped lang="less">
.part {
  width:80%;
}
.text-practice-progress{
  position: fixed;
  width: 90%;
  transform: translateX(-50%);
  bottom: 0;
  left: 50%;
}
.chinese-input-box{
  position: fixed;
  right: 50px;
  bottom: 50vh;
  .chinese-input{
    width: 1em;
    height: 1em;
    padding: 0.5em;
    font-size: 45px;
    caret-color: var(--theme-color);
    border-radius: 0.2em;
    color: var(--theme-color);
    outline: none;
    &:focus{
      border:2px solid var(--theme-color);
    }
  }
  .jump{
    animation: 0.5s swing-col infinite alternate;
  }

}

</style>